<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
class Shoppingcart_model extends CI_Model {
	public function __construct() {
		parent::__construct ();
	}
	/*
	 * 根据用户ID找到对应的购物车
	 */
	public function find_by_user($userid){
		$this->db->select('t_shoppingcart.id,t_shoppingcart.productid,t_shoppingcart.amount,t_shoppingcart.date,t_shoppingcart.type,t_product.name,t_product.image,t_product.description,t_product.price,t_product.unit');
		$this->db->from('t_shoppingcart');
		$this->db->where('userid',$userid);
		$this->db->join('t_product', 't_shoppingcart.productid = t_product.id','left');
		$this->db->order_by("date");
		$query = $this->db->get();
		return $query->result_array();
	}
	/*
	 * 根据用户ID,商品ID和日期查找购物车(显示该商品是否已购买)
	 */
	public function find_by_user_product_date($userid,$productid,$date){
		$this->db->select('id,amount');
		$this->db->where('userid', $userid);
		$this->db->where('productid', $productid);
		$this->db->where('date',$date);
		$query = $this->db->get('t_shoppingcart');
		return $query->row_array();
	}
	/*
	 * 根据用户ID,日期和类型查找购物车(用户某天某餐是否已订)
	 */
	public function find_by_user_date_type($userid,$date,$type){
		$this->db->select('t_shoppingcart.id,t_shoppingcart.productid,t_shoppingcart.amount,t_product.price');
		$this->db->from('t_shoppingcart');
		$this->db->join('t_product', 't_shoppingcart.productid = t_product.id','left');
		$this->db->where('userid',$userid);
		$this->db->where('date',$date);
		$this->db->where('type',$type);
		$query = $this->db->get();
		return $query->row_array();
	}
	/*
	 * 添加新的商品到购物车中
	 */
	public function create($shoppingcart){
		$this->db->insert('t_shoppingcart', $shoppingcart);
		return $this->db->insert_id();
	}
	/*
	 * 更新购物车中的商品信息
	 */
	public function update($id,$shoppingcart){
		$this->db->where('id', $id);
		$this->db->update('t_shoppingcart', $shoppingcart);
		return $this->db->affected_rows()>0;
	}
	/*
	 * 移除购物车中的商品
	 */
	public function delete($id){
		$this->db->where('id', $id);
		$this->db->delete('t_shoppingcart');
		return $this->db->affected_rows()>0;
	}
	/*
	 * 清空购物车
	 */
	public function delete_by_user($userid){
		$this->db->where('userid', $userid);
		$this->db->delete('t_shoppingcart');
		return $this->db->affected_rows()>0;
	}

	
	/*
	 * 根据ID得到购物车信息
	 */
	public function load($id){//
		if (!$id){
			return array();
		}
		$this->db->where('id',$id);
		$query = $this->db->get('t_shoppingcart');
		if ($row = $query->row_array()){
			return $row;
		}
		return array();
	}
}